package com.bootdo.system.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import javax.imageio.ImageIO;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.DistConfigValueService;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.BuildTree;
import com.bootdo.common.utils.DaYuSms;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.FileType;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.ImageUtils;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.UserType;
import com.bootdo.hjh.cache.DefaultNodeInfo;
import com.bootdo.hjh.cache.MemberCache;
import com.bootdo.hjh.cache.Node;
import com.bootdo.hjh.dao.SmsVerificationMapper;
import com.bootdo.hjh.domain.SmsVerification;
import com.bootdo.hjh.domain.UserAddress;
import com.bootdo.hjh.domain.UserExt;
import com.bootdo.hjh.ex.BizException;
import com.bootdo.hjh.ex.ThrowUtils;
import com.bootdo.hjh.service.OrderService;
import com.bootdo.hjh.service.UserAddressService;
import com.bootdo.hjh.vo.MemberRegVO;
import com.bootdo.system.dao.DeptDao;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.dao.UserRoleDao;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserRoleDO;
import com.bootdo.system.service.UserService;
import com.bootdo.system.vo.ProfileVO;
import com.bootdo.system.vo.UserVO;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	UserDao userMapper;
	@Autowired
	UserRoleDao userRoleMapper;
	@Autowired
	DeptDao deptMapper;
	@Autowired
	private FileService sysFileService;
	@Autowired
	private BootdoConfig bootdoConfig;

	@Autowired
	UserAddressService userAddressService;
	@Autowired
	OrderService orderService;

	@Autowired
    MemberCache memberCache;

	@Autowired
	DaYuSms daYuSms;

	@Autowired
	private DistConfigValueService distConfigValueService;

	@Autowired
	SmsVerificationMapper smsVerificationMapper;

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);

	@Override
	public UserDO get(Long id) {
		List<Long> roleIds = userRoleMapper.listRoleId(id);
		UserDO user = userMapper.get(id);
		if(user!=null){
			if(user.getDeptId()!=null){
				DeptDO dept = deptMapper.get(user.getDeptId());
				if(dept!=null){
					user.setDeptName(dept.getName());
				}
			}
			user.setRoleIds(roleIds);
		}
		return user;
	}

	@Override
	public List<UserDO> list(Map<String, Object> map) {
		return userMapper.list(map);
	}

	@Override
	public int count(Map<String, Object> map) {
		return userMapper.count(map);
	}

	@Transactional
	@Override
	public int save(UserDO user) {
		int count = userMapper.save(user);
		Long userId = user.getUserId();
		List<Long> roles = user.getRoleIds();
		userRoleMapper.removeByUserId(userId);
		List<UserRoleDO> list = new ArrayList<>();
		if (!CollectionUtils.isEmpty(roles)) {
			for (Long roleId : roles) {
				UserRoleDO ur = new UserRoleDO();
				ur.setUserId(userId);
				ur.setRoleId(roleId);
				list.add(ur);
			}
		}

		if (list.size() > 0) {
			userRoleMapper.batchSave(list);
		}
		return count;
	}

	@Override
	public int update(UserDO user) {
		int r = userMapper.update(user);
		Long userId = user.getUserId();
		List<Long> roles = user.getRoleIds();
		userRoleMapper.removeByUserId(userId);
		List<UserRoleDO> list = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(roles)) {
			for (Long roleId : roles) {
				UserRoleDO ur = new UserRoleDO();
				ur.setUserId(userId);
				ur.setRoleId(roleId);
				list.add(ur);
			}
			if (list.size() > 0) {
				userRoleMapper.batchSave(list);
			}
		}
		return r;
	}

	@Override
	public int remove(Long userId) {
		userRoleMapper.removeByUserId(userId);
		return userMapper.remove(userId);
	}

	@Override
	public boolean exit(Map<String, Object> params) {
		boolean exit;
		exit = userMapper.list(params).size() > 0;
		return exit;
	}

	@Override
	public Set<String> listRoles(Long userId) {
		return null;
	}

	@Override
	public int resetPwd(UserVO userVO,UserDO userDO) throws Exception {
		if(Objects.equals(userVO.getUserDO().getUserId(),userDO.getUserId())){
			if(Objects.equals(MD5Utils.encrypt(userDO.getUsername(),userVO.getPwdOld()),userDO.getPassword())){
				userDO.setPassword(MD5Utils.encrypt(userDO.getUsername(),userVO.getPwdNew()));
				return userMapper.update(userDO);
			}else{
				throw new Exception("输入的旧密码有误！");
			}
		}else{
			throw new Exception("你修改的不是你登录的账号！");
		}
	}
	@Override
	public int adminResetPwd(UserVO userVO) throws Exception {
		UserDO userDO =get(userVO.getUserDO().getUserId());
		//if("admin".equals(userDO.getUsername())){
			//throw new Exception("超级管理员的账号不允许直接重置！");
		//}
		userDO.setPassword(MD5Utils.encrypt(userDO.getUsername(), userVO.getPwdNew()));
		return userMapper.update(userDO);
	}

	@Override
	public int adminResetPayPwd(UserVO userVO) throws Exception {
		UserDO userDO = get(userVO.getUserDO().getUserId());
		userDO.setPayPwd(MD5Utils.encrypt(userVO.getPwdNew()) );
		return userMapper.update(userDO);
	}

	@Override
	public int adminResetParent(UserVO userVO) throws Exception {
		String ecommendUserNameNew = userVO.getRecommendUserNameNew();
		UserDO userDO = get(userVO.getUserDO().getUserId());
		if (ecommendUserNameNew.equals(userDO.getUsername())) {
			throw new BizException("不能设置自己作为自己的上级", 1002);
		}
		UserDO byUsername = getByUsername(ecommendUserNameNew);
		if (byUsername == null) {
			throw new BizException("您指定的上级不存在", 1003);
		}
		if (userDO.getRecommendUserId()!=null && userDO.getRecommendUserId().equals(byUsername.getUserId())) {
			// 没有变化
			return 0;
		}
		userDO.setRecommendUserId(byUsername.getUserId());
		userDO.setStartUserId(byUsername.getStartUserId());
		userDO.setRecommendUserName(ecommendUserNameNew);
		int cnt = userMapper.update(userDO);

		// 更新缓存
		memberCache.reloadCacheFromDb();

		return cnt;
	}

	@Transactional
	@Override
	public int batchremove(Long[] userIds) {
		int count = userMapper.batchRemove(userIds);
		userRoleMapper.batchRemoveByUserId(userIds);
		return count;
	}

	@Override
	public Tree<DeptDO> getTree() {
		List<Tree<DeptDO>> trees = new ArrayList<Tree<DeptDO>>();
		List<DeptDO> depts = deptMapper.list(new HashMap<String, Object>(16));
		Long[] pDepts = deptMapper.listParentDept();
		Long[] uDepts = userMapper.listAllDept();
		Long[] allDepts = (Long[]) ArrayUtils.addAll(pDepts, uDepts);
		for (DeptDO dept : depts) {
			if (!ArrayUtils.contains(allDepts, dept.getDeptId())) {
				continue;
			}
			Tree<DeptDO> tree = new Tree<DeptDO>();
			tree.setId(dept.getDeptId().toString());
			tree.setParentId(dept.getParentId().toString());
			tree.setText(dept.getName());
			Map<String, Object> state = new HashMap<>(16);
			state.put("opened", true);
			state.put("mType", "dept");
			tree.setState(state);
			trees.add(tree);
		}
		List<UserDO> users = userMapper.list(new HashMap<String, Object>(16));
		for (UserDO user : users) {
			Tree<DeptDO> tree = new Tree<DeptDO>();
			tree.setId(user.getUserId().toString());
			tree.setParentId(user.getDeptId().toString());
			tree.setText(user.getName());
			Map<String, Object> state = new HashMap<>(16);
			state.put("opened", true);
			state.put("mType", "user");
			tree.setState(state);
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		Tree<DeptDO> t = BuildTree.build(trees);
		return t;
	}

	@Override
	public int updatePersonal(UserDO userDO) {
		return userMapper.update(userDO);
	}

    @Override
    public Map<String, Object> updatePersonalImg(MultipartFile file, String avatar_data, Long userId) throws Exception {
		String fileName = file.getOriginalFilename();
		fileName = FileUtil.renameToUUID(fileName);
		FileDO sysFile = new FileDO(FileType.fileType(fileName), "/files/" + fileName, new Date());
		//获取图片后缀
		String prefix = fileName.substring((fileName.lastIndexOf(".")+1));
		String[] str=avatar_data.split(",");
		//获取截取的x坐标
		int x = (int)Math.floor(Double.parseDouble(str[0].split(":")[1]));
		//获取截取的y坐标
		int y = (int)Math.floor(Double.parseDouble(str[1].split(":")[1]));
		//获取截取的高度
		int h = (int)Math.floor(Double.parseDouble(str[2].split(":")[1]));
		//获取截取的宽度
		int w = (int)Math.floor(Double.parseDouble(str[3].split(":")[1]));
		//获取旋转的角度
		int r = Integer.parseInt(str[4].split(":")[1].replaceAll("}", ""));
		try {
			BufferedImage cutImage = ImageUtils.cutImage(file,x,y,w,h,prefix);
			BufferedImage rotateImage = ImageUtils.rotateImage(cutImage, r);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			boolean flag = ImageIO.write(rotateImage, prefix, out);
			//转换后存入数据库
			byte[] b = out.toByteArray();
			FileUtil.uploadFile(b, bootdoConfig.getUploadPath(), fileName);
		} catch (Exception e) {
			throw  new Exception("图片裁剪错误！！");
		}
		Map<String, Object> result = new HashMap<>();
		if(sysFileService.save(sysFile)>0){
			UserDO userDO = new UserDO();
			userDO.setUserId(userId);
			userDO.setPicId(sysFile.getId());
			if(userMapper.update(userDO)>0){
				result.put("url",sysFile.getUrl());
			}
		}
		return result;
    }

	@Override
	public int saveMember(MemberRegVO memberRegVO,Long invokeUserId) {

		UserDO  sysUser = userMapper.getByUsername(memberRegVO.getUsername());
		ThrowUtils.throwCondition(sysUser!=null,101,"用户名"+memberRegVO.getUsername()+"已经存在");

		String recommendUsername = memberRegVO.getRecommendUsername();
		UserDO recommendUserDO = userMapper.getByUsername(recommendUsername);
		ThrowUtils.throwCondition(recommendUserDO==null,101,"推荐人不存在");
		ThrowUtils.throwCondition(recommendUserDO.getAgentLevel() == null || recommendUserDO.getAgentLevel() <= 0, 101,
				"只有代理及以上才能注册会员");


		memberRegVO.setRecommendUserId(recommendUserDO.getUserId());

		Node parentNode = memberCache.getNode(recommendUserDO.getUserId());

		UserDO user = memberRegVO.toUserDO();
		user.setType(UserType.MEMBER);
		user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
		user.setLevel(parentNode.getLevel()+1);
		user.setStartUserId(parentNode.getInfo().getRootId());
		int result = save(user);

		if(result>0){
			Long newUserId = user.getUserId();
			memberRegVO.setUserId(newUserId);
			//1 保存地址
			UserAddress address = new UserAddress();
			address.setUserId(newUserId);
			address.setName(memberRegVO.getReceiveName());
			address.setMobile(memberRegVO.getReceiveMobile());
			address.setAddress(memberRegVO.getReceiveAddress());
			userAddressService.addUserAddress(address);

			Integer addressId = address.getId();
			//2 生成订单
			orderService.createOrder(invokeUserId,newUserId,memberRegVO.getProductId(),
					memberRegVO.getQuantity(),addressId, recommendUserDO.getUserId());
			//3 更新缓存
			memberCache.addNode(memberRegVO.getUserId());
		}
		return result;
	}

	@Override
	public int updateProfile(ProfileVO profileVO) {

		return userMapper.updateProfile(profileVO);
	}

	@Override
	public Integer updatePayPwd(ProfileVO profileVO) {

		return userMapper.updatePayPwd(profileVO);
	}

	@Override
	public Integer updateLoginPwd(ProfileVO profileVO) {
		return userMapper.updateLoginPwd(profileVO);
	}

	@Override
	public Integer updateMobile(String mobile, Long userId) {
		return userMapper.updateMobile(mobile,userId);
	}

	@Override
	public Integer updateEmail(String email, Long userId) {
		return userMapper.updateEmail(email,userId);
	}

	@Override
	public List<String> searchUser(String keyword, Long userId, boolean findChildren) {

		List<String> list = null;
		if(findChildren){
			list = memberCache.searchUserByName(keyword,userId);
		}else{
			keyword = StringUtils.isNotBlank(keyword)?keyword.concat("%"):"";
			list = userMapper.searchUserByName(keyword);
		}
		return list;
	}

	@Override
	public UserDO getByUsername(String username) {
		UserDO user = userMapper.getByUsername(username);
		return user;
	}

	@Override
	public List<DefaultNodeInfo> myTeamNodeList(Long userId) {
		UserDO userDO = userMapper.get(userId);
		List<DefaultNodeInfo> children = userMapper.selectChildrenOfRoot(userId, userDO.getLevel(), 0, 100);

		return children;
	}

	@Override
	public boolean sendVerification(String mobile, Long userId) {

		//获取最近的一条短信验证码
		SmsVerification lastSms = smsVerificationMapper.lastSmsVerification(mobile);
		//30 秒内不能重复发送验证码

		ThrowUtils.throwCondition(
				lastSms!=null && lastSms.getIsUsed()==0 && System.currentTimeMillis()-lastSms.getCreateTime().getTime()<120000L,
				100,
				"短信已经发送，请勿频繁操作"
				);


		daYuSms.sendVerification(mobile,userId);
		return true;
	}

	@Override
	public boolean forgetPassword(String mobile, String vcode, String password) {
		UserDO userDO = userMapper.getByMobile(mobile);
		ThrowUtils.throwCondition(userDO==null,100,"用户不存在");
		SmsVerification verification = smsVerificationMapper.lastSmsVerification(mobile);
		ThrowUtils.throwCondition(verification==null,102,"验证码错误");
		ThrowUtils.throwCondition(verification.getIsUsed()!=null && verification.getIsUsed()==1,102,"验证码已被使用，请重新请求");
		ThrowUtils.throwCondition(verification.getCreateTime()!=null && (System.currentTimeMillis()-verification.getCreateTime().getTime())>=30*60*1000L,102,"验证码已过期");
		ThrowUtils.throwCondition(!StringUtils.equals(vcode,verification.getCode()),102,"验证码已错误");

		String newPassword = MD5Utils.encrypt(userDO.getUsername(),password);
		userDO.setPassword(newPassword);
		userMapper.updateLoginPwd1(newPassword,userDO.getUserId());
		//标记为已使用
		smsVerificationMapper.usedSmsVerification(verification.getId());
		return true;
	}

	@Override
	public int countFirstRecommend(Long userId) {
		return memberCache.countFirstRecommend(userId);
	}

	@Override
	public int countSecondRecommend(Long userId) {
		return memberCache.countSecondRecommend(userId);
	}

	@Override
	public Integer insertUserExt(Long userId) {
		UserExt ue = userMapper.getUserExt(userId);
		if(null == ue) {
			userMapper.insertUserExt(userId);
		}
		return 1;
	}

	@Override
	public Integer updateUserExtAgent(Long userId) {
		insertUserExt(userId);
		userMapper.updateUserExtAgent(userId);
		return 1;
	}

	@Override
	public UserDO getUserByUsername(String username) {
		UserDO  sysUser = userMapper.getByUsername(username);
		return sysUser;
	}

	public List<Integer> achievement(String startDate,String endDate) throws Exception{
		List<Integer> data = new ArrayList<>();
		int diffDay = 10;
		if(null != startDate && null != endDate) {
			diffDay = DateUtils.daysOfTwo(DateUtils.StrToDate(endDate, DateUtils.DATE_PATTERN),DateUtils.StrToDate(startDate, DateUtils.DATE_PATTERN));
		}else {
			Date now = DateTime.now().toDate();
			endDate = DateUtils.format(now, DateUtils.DATE_PATTERN);
			Date daysAgo = DateTime.now().minusDays(diffDay - 1).toDate();
			startDate = DateUtils.format(daysAgo, DateUtils.DATE_PATTERN);
		}
//		logger.info("startDate : {} endDate : {}",startDate,endDate);
		for(int i = 0;i<diffDay;i++) {
			data.add(0);
		}
		Date now = DateTime.now().toDate();
//		logger.info("startDate : {} endDate : {}",startDate,endDate);
		List<UserDO> userList = userMapper.achievement(startDate, endDate);
		if(null != userList && !userList.isEmpty()) {
			for(UserDO userDO : userList) {
				int diff = DateUtils.daysOfTwo(now,userDO.getActiveTime());
				int idx = ((diffDay - 1) - diff)%10;
//				logger.info("now : {},activeTime : {} diff : {} ,idx : {} ",DateUtils.format(now, DateUtils.DATE_PATTERN),DateUtils.format(userDO.getActiveTime(), DateUtils.DATE_PATTERN),diff,idx);

				data.set(idx,  data.get(idx) + 1);
			}
		}
		return data;
	}

	@Override
	public List<String> achievementDate(String startDate,String endDate) throws Exception {
		int diffDay  = 10;
		List<String> result = new ArrayList<>();
		if(null != startDate && endDate != null) {
			diffDay = DateUtils.daysOfTwo(DateUtils.StrToDate(endDate, DateUtils.DATE_PATTERN),DateUtils.StrToDate(startDate, DateUtils.DATE_PATTERN));
		}else {
			Date now = DateTime.now().toDate();
			endDate = DateUtils.format(now, DateUtils.DATE_PATTERN);
			Date daysAgo = DateTime.now().minusDays(diffDay - 1).toDate();
			startDate = DateUtils.format(daysAgo, DateUtils.DATE_PATTERN);
		}
		for(int i = (diffDay - 1);i >= 0;i--) {
			Date daysAgo = DateTime.now().minusDays(i).toDate();
			String eDate = DateUtils.format(daysAgo, DateUtils.DATE_PATTERN);
			result.add(eDate);
		}
		return result;
	}


	@Override
	public List<String> achievementDateMonth(String startDate,String endDate) throws Exception {
		int diffDay  = 12;
		List<String> result = new ArrayList<>();
		if(null != startDate && endDate != null) {
			diffDay = DateUtils.daysOfTwoMonth(DateUtils.StrToDate(endDate, DateUtils.MONTH_PATTERN),DateUtils.StrToDate(startDate, DateUtils.MONTH_PATTERN));
		}else {
			Date now = DateTime.now().toDate();
			endDate = DateUtils.format(now, DateUtils.MONTH_PATTERN);
			Date daysAgo = DateTime.now().minusMonths(diffDay - 1).toDate();
			startDate = DateUtils.format(daysAgo, DateUtils.MONTH_PATTERN);
		}
		for(int i = (diffDay - 1);i >= 0;i--) {
			Date daysAgo = DateTime.now().minusMonths(i).toDate();
			String eDate = DateUtils.format(daysAgo, DateUtils.MONTH_PATTERN);
			result.add(eDate);
		}
		return result;
	}

	@Override
	public List<UserDO> getUserDoByAgentLeel(Integer agentLevel) {
		if(agentLevel == null || agentLevel == 0) {
			return userMapper.getAllUserByAgentIsNull();
		}else {
			return userMapper.getAllUser(agentLevel);
		}

	}

	@Override
	public Integer saveReplenishment(Long createUserId, int amount, int type) {

		UserDO me = get(createUserId);

		// 上级代理
		String superiorUsername = memberCache.superior(createUserId);

		UserDO superior = userMapper.getByUsername(superiorUsername);

		if (superior == null) {
			throw new BizException("顶级用户不需要补货！", 2019);
		}
		// 生成订单
		Integer orderId = orderService.createBuhuoOrder(createUserId, superior.getUserId(), amount, type);

		return orderId;
	}

	@Override
	public Integer saveUpgrade(Long userId, String superior) {
		UserDO me = get(userId);

		Integer agentLevel = me.getAgentLevel();
		if (agentLevel != null && agentLevel >0) {
			throw new BizException("您已经是代理或代理也上了，无需升级", 1034);
		}

		UserDO superiorUser = getByUsername(superior);
		if (superiorUser == null) {
			throw new BizException("推荐人不存在", 1001);
		}
		if (superiorUser.getAgentLevel() == null || superiorUser.getAgentLevel() <= 0) {
			throw new BizException("推荐人不是代理或及以上", 1001);
		}
		// 生成订单
		// 老用户不需要分润
		Integer orderId = orderService.createUpgradeOrder(userId, superiorUser.getUserId(),
				me.getMemberLevel()!=null && me.getMemberLevel() > 3);

		return orderId;
	}

	@Override
	public void upgradeTrigger(Long userId) {
		// 计算一下上级的绩点
		caclSuperJd(userId);

		caclJd(userId);

		Node node = memberCache.getNode(userId);

		while (node != null) {
			// 当前级别
			int agentLevel = node.getInfo().getAgentLevel() == null ? 0 : node.getInfo().getAgentLevel();

			// 普通会员或操过高级会员将不能通过这种方式升级等级
			if (agentLevel<=0 || agentLevel>4 || node.getInfo().getActiveTime() == null) {
				node = node.getParent();
				continue;
			}

			List<Node> recommendNodeList = node.getRecommendNodeList();
			if (recommendNodeList != null && !recommendNodeList.isEmpty()) {

				// 升级所需绩点
				int needJd2Upgrade = getNeedPoint(agentLevel);
				// 绩点
				int jd = caclJd(node.getInfo().getUserId());

				// 绩点不足
				if (needJd2Upgrade > jd) {
					node = node.getParent();
					continue;
				}
				// 下级及以上人数
				int low = 0;
				for (Node temp : recommendNodeList) {
					if (temp.getInfo().getActiveTime() == null) {
						continue;
					}
					int tempAgentLevel = temp.getInfo().getAgentLevel() == null ? 0 : temp.getInfo().getAgentLevel();
					if (tempAgentLevel >= (agentLevel - 1)) {
						low ++;
					}
				}

				// 所需下级人数
				int needLower = getNeedLower(agentLevel);

				// 满足升级条件
				if (low >= needLower) {
					// 更新数据库
					userMapper.updateAgentLevel(agentLevel+1, node.getInfo().getUserId());
					// 更新缓存
					node.getInfo().setAgentLevel(agentLevel + 1);

					// 上级的绩点需要重新计算
					caclSuperJd(node.getInfo().getUserId());

				}
			}
			// 向上追溯
			node = node.getParent();
		}
	}

	@Override
	public void caclSuperJd(Long userId) {
		Node node = memberCache.getNode(userId);
		if (node == null) {
			return;
		}

		Node parent = node.getParent();
		if (parent == null || parent.getInfo().getActiveTime() == null) {
			return;
		}

		// old 绩点
		int oldJd = parent.getInfo().getPoints() == null ? 0: parent.getInfo().getPoints();
		// 绩点
		int jd = 0;
		// 推荐人
		List<Node> recommendNodeList = parent.getRecommendNodeList();
		for (Node temp : recommendNodeList) {

			int tempAgentLevel = temp.getInfo().getAgentLevel() == null ? 0 : temp.getInfo().getAgentLevel();
			if (temp.getInfo().getActiveTime() == null) {
				continue;
			}
			jd += getHelpPoint(tempAgentLevel);

		}

		if (jd != oldJd) {
			// 更新数据库
			userMapper.updatePoints(jd, parent.getInfo().getUserId());

			// 更新缓存
			parent.getInfo().setPoints(jd);
			// 是否触发本身级别变更, 不用做，因为本身向上追溯
		}

	}

	@Override
	public int caclJd(Long userId) {
		Node node = memberCache.getNode(userId);
		if (node == null || node.getInfo().getActiveTime()==null) {
			return 0;
		}
		// old 绩点
		int oldJd = node.getInfo().getPoints() == null ? 0: node.getInfo().getPoints();

		// 绩点
		int jd = 0;

		// 推荐人
		List<Node> recommendNodeList = node.getRecommendNodeList();
		for (Node temp : recommendNodeList) {

			int tempAgentLevel = temp.getInfo().getAgentLevel() == null ? 0 : temp.getInfo().getAgentLevel();
			if (temp.getInfo().getActiveTime() == null) {
				continue;
			}
			jd += getHelpPoint(tempAgentLevel);

		}

		if (jd != oldJd) {
			// 更新数据库
			userMapper.updatePoints(jd, node.getInfo().getUserId());

			// 更新缓存
			node.getInfo().setPoints(jd);
			// 是否触发本身级别变更, 不用做，因为本身向上追溯
		}
		return jd;
	}

	// 升级等级所需绩点
	private int getNeedPoint(Integer agentLevel) {
		if (agentLevel != null && agentLevel > 0) {
			if (agentLevel == 1) {
				return distConfigValueService.getPROXY_UPGRADE_JD_MIN();
			} else if (agentLevel == 2) {
				return distConfigValueService.getJUNIOR_PARTNER_UPGRADE_JD_MIN();
			} else if (agentLevel == 3) {
				return distConfigValueService.getINTERMEDIATE_PARTNER_UPGRADE_JD_MIN();
			} else if (agentLevel == 4) {
				return distConfigValueService.getSENIOR_PARTNER_UPGRADE_JD_MIN();
			}
		}
		return Integer.MAX_VALUE;
	}

	// 升级等级所需下级及以上人数
	private int getNeedLower(Integer agentLevel) {
		if (agentLevel != null && agentLevel > 0) {
			if (agentLevel == 1) {
				return distConfigValueService.getPROXY_UPGRADE_LOWER_MIN();
			} else if (agentLevel == 2) {
				return distConfigValueService.getJUNIOR_PARTNER_UPGRADE_LOWER_MIN();
			} else if (agentLevel == 3) {
				return distConfigValueService.getINTERMEDIATE_PARTNER_UPGRADE_LOWER_MIN();
			} else if (agentLevel == 4) {
				return distConfigValueService.getSENIOR_PARTNER_UPGRADE_LOWER_MIN();
			}
		}
		return Integer.MAX_VALUE;
	}

	/**
	 * 获取代理级别的贡献点
	 * @param agentLevel：代理级别 1:代理 2:初级合伙人 3:中级合伙人 4:高级合伙人 5:特级合伙人
	 * @return
	 */
	private int getHelpPoint(Integer agentLevel) {
		if (agentLevel == null || agentLevel <= 0) {
			return 0;
		}
		if (agentLevel == 1) {
			return distConfigValueService.getPROXY_HELPED_POINT();
		} else if (agentLevel == 2) {
			return distConfigValueService.getJUNIOR_PARTNER_HELPED_POINT();
		} else if (agentLevel == 3) {
			return distConfigValueService.getINTERMEDIATE_PARTNER_HELPED_POINT();
		} else if (agentLevel == 4) {
			return distConfigValueService.getSENIOR_PARTNER_HELPED_POINT();
		} else if (agentLevel == 5) {
			return distConfigValueService.getCOFOUNDER_HELPED_POINT();
		}
		return 0;
	}

}
